/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2020-1-1
 */

const App = getApp();
const func = require('../../utils/func.js');
import wxParse from '../../wxParse/wxParse.js'; // 富文本插件

Page({

	data: {
		hotSearch: [],
		scrollbar: false,
		enhanced: true,
		list: [],
		page: 1,
		no_more: false,
		isLoading: true,
		seckillStart:'',
		couponList:[],
		scrollbar:false,
		opcity:0,
		inputTop: 0, //搜索框距离顶部距离
		arrowTop: 0, //箭头距离顶部距离
		dropScreenH: 0, //下拉筛选框距顶部距离
		enhanced:true,
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function() {
		let _this = this,
		obj = wx.getMenuButtonBoundingClientRect();
		_this.setData({
			width: obj.left,
			height:( obj.top + obj.height + 12 ) * 2,
			inputTop: obj.top + (obj.height - 30) / 2,
			arrowTop: obj.top + (obj.height - 32) / 2,
		}, () => {
			wx.getSystemInfo({
				success: (res) => {
					_this.setData({
						statusBarHeight:res.statusBarHeight,
					scrollH: res.windowWidth,
						//略小，避免误差带来的影响
						dropScreenH: _this.data.height * 750 / res.windowWidth +
							86,
						drawerH: res.windowHeight - res.windowWidth / 750 *
							100 - _this.data.height
					})
				}
			})
		});
		// _this.getPageData(); // 加载页面数据
	},
	/**
	 * 生命周期回调—监听页面显示
	 */
	onShow() {
		let _this = this;
		if(!App.checkIsLogin()) {
            App.defaultLogin(_this);
		} 
		this.getPageData()
	},
	onPageScroll(e) {
		
		let scroll = e.scrollTop <= 0 ? 0 : e.scrollTop;
		let opcity = scroll / this.data.scrollH;
		if (this.data.opcity >= 1 && opcity >= 1) {
			return;
		}
		this.setData({
			opcity: opcity,
			iconOpcity: 0.5 * (1 - opcity < 0 ? 0 : 1 - opcity)
		})
	},
	/**
	 * 加载页面数据
	 */
	getPageData: function() {
		let _this = this;
		App._requestApi(_this, App.globalData.config.apiIndexUrl, {
			apiAdv_1: `ekey=1&pid=4`, // 金刚位标签adv
			apiAdv_2: `ekey=2&pid=2`, // 轮播图标签adv
			apiArclist_1: `ekey=1&channel=2&pagesize=6&label=2&orderby=total_sales_num&orderway=desc`, //列表不涉及分页   爆款
			apiArclist_2: `ekey=2&channel=2&pagesize=6&label=5&page=1&orderby=total_sales_num&orderway=desc`, // 上新列表设计分页  新品热销
			apiList_1: `ekey=1&channel=2&pagesize=6&label=1&page=1`, //涉及分页
			apiCouponList_1: `ekey=1&page=1`, // 领取优惠券列表
			apiSeckillTime_1: `ekey=1&pagesize`, //秒杀
			apiHotSearch_1: `ekey=1&pagesize=5&is_hot=1`,
			apiGlobal: `ekey=1`, // 全局配置变量标签global
			// 这里可以根据需求填写更多的api标签
		}, function(res) {
			if (res.data.cart_total_num > 0) {
				wx.setTabBarBadge({
					index: 2,
					text: String(res.data.cart_total_num)
				});
			} else if(res.data.cart_total_num == 0){
			  wx.removeTabBarBadge({
			        index: 2
			    });
			}
		
			// 特别说明：中括号[1]的数字必须与api标签的参数ekey=1值对应，否则数据对不上。
			let adv_1 = res.data.apiAdv[1],
				adv_2 = res.data.apiAdv[2], // adv广告位数据
				arclist_1 = res.data.apiArclist[1], // 第一个arclist文档列表数据
				arclist_2 = res.data.apiArclist[2], // 第一个arclist文档列表数据
				productList_1 = res.data.apiList[1], 
				couponList = res.data.apiCouponList[1], // 
				apiSeckillTime_1= res.data.apiSeckillTime[1], //第一个秒杀场次数据
				apiHotSearch = res.data.apiHotSearch[1],
				global = res.data.apiGlobal[1]; // global全局配置变量数据

			// 设置导航标题
			wx.setNavigationBarTitle({
				title: global.data.web_name || '易优CMS小程序'
			})
			let seckillStart = '';
			
			if (apiSeckillTime_1) {
				if (apiSeckillTime_1.status == 10) {
					seckillStart =  apiSeckillTime_1.end_time_arr.time - Date.parse(new Date()) / 1000;    //秒杀时间已经开始时间差
				} else if (apiSeckillTime_1.status == 20) {
					seckillStart = apiSeckillTime_1.start_time_arr.time - Date.parse(new Date()) / 1000;
				}
			}
		
			_this.setData({
				adv_1,
				adv_2,
				arclist_1,
				arclist_2,
				productList_1,
				apiSeckillTime_1,
				apiHotSearch,
				global,
				seckillStart,
				couponList,
				isLoading: false
			});
		});
	
	},

	getCoupon: function(e) {
		let _this = this;
		App._requestPost(_this, App.globalData.config.apiGetCouponUrl, {
			coupon_id: e.currentTarget.dataset.id
		}, function(result) {
			if (1 == result.code) {
				let index = e.currentTarget.dataset.index;
				_this.setData({
					['couponList.data[' + index + ']']: result.data.coupon_data
				})
				wx.showToast({
					title: result.msg,
					icon: 'success',
					duration: 1000
				})
			}
		});
	},
	getMoreList(isPage, page) {
		let _this = this;
		page = page || 1;
		App._requestApi(_this, App.globalData.config.apiIndexUrl, {
			apiList_1: `ekey=1&channel=2&pagesize=6&label=1&page=` + page,
		}, function(res) {
			let productList_1 = res.data.apiList[1]; // 第一个list文档列表数据
			if (isPage == true) {
				let dataList = _this.data.productList_1;
				_this.setData({
					'productList_1.data': dataList.data.concat(productList_1.data),
					isLoading: false
				})
			} else {
				_this.setData({
					productList_1,
					isLoading: false
				})
			}
		});
	},
	// 触底加载
	onReachBottom() {
    let _this = this;
		if (_this.data.page >= _this.data.productList_1.last_page) {
			_this.setData({
				no_more: true
			});
			return false;
    }
		_this.getMoreList(true, ++_this.data.page);
	},

	// 跳转到分类列表
	more: function(e) {
		let key = e.currentTarget.dataset.key || '';
		wx.navigateTo({
			url: `/pages/product/list?searchKey=${key}`,
		})
	},
	navLink(e) {
		let _this = this
		let typeid = e.currentTarget.dataset.item.typeid;
		let f_cur = e.currentTarget.dataset.item.f_cur;
		let tips = e.currentTarget.dataset.item.tips;
		let type = e.currentTarget.dataset.item.type;
		if (typeid == 1) {
			if (!_this.data.Discountactive || type == 'jifen') {
				wx.showToast({
					icon: 'none',
					title: e.currentTarget.dataset.item.tips,
					duration: 1000
				});
			} else {
				let active_id = _this.data.Discountactive.active_id
				wx.navigateTo({
					url: `/pages/discount/index?active_id=${active_id}`
				})
			}
		} else {
			wx.reLaunch({
				url: `/pages/category/index?typeid=${typeid}&f_cur=${f_cur}`
			})
		}
	},
	/**
	 * 下拉刷新
	 */
	onPullDownRefresh: function() {
		this.getPageData(); // 获取首页数据

		wx.stopPullDownRefresh(); // 停止下拉刷新
	},
	/**
	 * 分享当前页面
	 */
	onShareAppMessage() {
		let _this = this;
		return {
			title: _this.data.page.params.title,
			path: "/pages/index/index?" + App.getShareUrlParams()
		};
	},
	/**
	 * 分享到朋友圈
	 */
	onShareTimeline() {
		let _this = this;
		return {
			title: _this.data.page.params.title,
		}
	},
	/**
	 * 地图导航
	 */
	gomap: function(e) {
		let coordinate = e.currentTarget.dataset.coordinate || '19.992555,110.339932';
		if (coordinate) {
			let address = e.currentTarget.dataset.address || '';
			let map = coordinate.split(',');
			wx.openLocation({
				latitude: parseFloat(map[0]),
				longitude: parseFloat(map[1]),
				address: address
			})
		}
	},
	// 跳转到其他界面
	jumpToView(e) {
		func.jumpToUrl(e)
	}
});
